package com.job.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.job.common.Check;
import com.job.common.Constant;
import com.job.common.ResponseResult;
import com.job.common.asserts.MyAssert;
import com.job.common.converter.StudentFieldConverter;
import com.job.common.enums.ResultCodeEnum;
import com.job.common.exception.ParameterIsNullException;
import com.job.controller.req.StudentCertificateVO;
import com.job.mapper.*;
import com.job.pojo.*;
import com.job.pojo.vo.StudentVO;
import com.job.service.StudentService;
import com.job.util.OssUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StudentInfoServiceImpl implements StudentService, Constant {

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private WorkInfoMapper workInfoMapper;

    @Resource
    private ProductInfoMapper productInfoMapper;

    @Resource
    private EducationMapper educationMapper;

    @Resource
    private CertificateMapper certificateMapper;

    @Resource
    private OwnMapper ownMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private StudentFieldConverter studentFieldConverter;


    @Override
    public ResponseResult<StudentVO> studentInfoQuery(String studentId) {
        int sid = Check.checkAndReturnId(studentId);
        if (sid == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<StudentVO>().setCode(400).setMessage("id不合法");
        }
        Student student = queryStudentId(studentId);
        StudentVO studentVO = studentFieldConverter.studentPoToVo(student);
        if (Objects.isNull(student)){
            log.info("用户不存在");
            return new ResponseResult<StudentVO>().setCode(400).setMessage("用户不存在");
        }

        return new ResponseResult<StudentVO>().success(studentVO);
    }

    @Override
    public ResponseResult<List<WorkInfo>> studentWorkInfoQuery(String studentId) {
        int sid = Check.checkAndReturnId(studentId);
        if (sid == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<List<WorkInfo>>().setCode(400).setMessage("id不合法");
        }

        if (Objects.isNull(queryStudentId(studentId))){
            log.info("用户不存在");
            return new ResponseResult<List<WorkInfo>>().setCode(400).setMessage("用户不存在");
        }

        LambdaQueryWrapper<WorkInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkInfo::getStudentId,sid);
        List<WorkInfo> workInfos = workInfoMapper.selectList(wrapper);

        if (CollectionUtils.isEmpty(workInfos)){
            log.info("实习经历不存在");
            return new ResponseResult<List<WorkInfo>>().setCode(400).setMessage("你没有实习经历,请填写");
        }

        return new ResponseResult<List<WorkInfo>>().success(workInfos);
    }

    @Override
    public ResponseResult<List<Product>> studentProductInfoQuery(String studentId) {
        int sid = Check.checkAndReturnId(studentId);
        if (sid == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<List<Product>>().setCode(400).setMessage("id不合法");
        }

        if (Objects.isNull(queryStudentId(studentId))){
            log.info("用户不存在");
            return new ResponseResult<List<Product>>().setCode(400).setMessage("用户不存在");
        }

        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getStudentId,sid);
        List<Product> products = productInfoMapper.selectList(wrapper);

        if (CollectionUtils.isEmpty(products)){
            return new ResponseResult<List<Product>>().setCode(400).setMessage("该学生没有实习经历，请填写");
        }

        return new ResponseResult<List<Product>>().success(products);
    }

    @Override
    public ResponseResult<List<Education>> studentEducationQuery(String studentId) {
        int sid = Check.checkAndReturnId(studentId);
        if (sid == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<List<Education>>().setCode(400).setMessage("id不合法");
        }

        if (Objects.isNull(queryStudentId(studentId))){
            log.info("用户不存在");
            return new ResponseResult<List<Education>>().setCode(400).setMessage("用户不存在");
        }

        LambdaQueryWrapper<Education> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Education::getStudentId,sid);
        List<Education> educations = educationMapper.selectList(wrapper);

        if (CollectionUtils.isEmpty(educations)){
            log.info("教学经历不存在");
            return new ResponseResult<List<Education>>().setCode(400).setMessage("你没有教育经历,请填写");
        }

        return new ResponseResult<List<Education>>().success(educations);

    }

    @Override
    public ResponseResult<List<Certificate>> studentCertificateQuery(String studentId) {
        int sid = Check.checkAndReturnId(studentId);
        if (sid == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<List<Certificate>>().setCode(400).setMessage("id不合法");
        }

        if (Objects.isNull(queryStudentId(studentId))){
            log.info("用户不存在");
            return new ResponseResult<List<Certificate>>().setCode(400).setMessage("用户不存在");
        }

        LambdaQueryWrapper<Own> ownWrapper = new LambdaQueryWrapper<>();
        ownWrapper.eq(Own::getStudent_id,studentId);
        List<Own> owns = ownMapper.selectList(ownWrapper);
        List<Integer> certificateId = owns.stream().map(Own::getCertificateId).collect(Collectors.toList());

        if (certificateId.isEmpty()){
            return new ResponseResult<List<Certificate>>().setCode(400).setMessage("你没有证书,请填写");
        }

        List<Certificate> certificates = certificateMapper.selectBatchIds(certificateId);

        if (certificates.isEmpty()){
            return new ResponseResult<List<Certificate>>().setCode(400).setMessage("你没有证书,请填写");
        }

        return new ResponseResult<List<Certificate>>().success(certificates);
    }

    @Override
    public ResponseResult<Student> studentInfoUpdate(Student student) {
        if (Objects.isNull(student)){
            log.info("参数为空");
            return new ResponseResult<Student>().setCode(400).setMessage("参数为空");
        }
        int res = studentMapper.updateById(student);
        if (res < 1){
            log.info("修改失败");
            return new ResponseResult<Student>().setCode(400).setMessage("修改失败");
        }

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getRoleId,student.getStudentId());
        wrapper.eq(User::getUserType,STUDENT);
        User user = userMapper.selectOne(wrapper);
        user.setNickName(student.getStudentName());

        if (userMapper.updateById(user) < 1){
            log.info("修改失败");
            return new ResponseResult<Student>().setCode(400).setMessage("修改失败");
        }

        return new ResponseResult<Student>().success();
    }

    @Override
    public ResponseResult<WorkInfo> studentWorkInfoUpdate(WorkInfo workInfo) {
        if (Objects.isNull(workInfo)){
            return new ResponseResult<WorkInfo>().setCode(400).setMessage("参数为空");
        }

        LambdaQueryWrapper<WorkInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkInfo::getId,workInfo.getId());
        int res = workInfoMapper.update(workInfo, wrapper);
        if (res < 1){
            log.info("修改失败");
            return new ResponseResult<WorkInfo>().setCode(400).setMessage("学生不存在");
        }

        return new ResponseResult<WorkInfo>().success();
    }

    @Override
    public ResponseResult<Product> studentProductInfoUpdate(Product product) {
        if (Objects.isNull(product)){
            return new ResponseResult<Product>().setCode(400).setMessage("参数为空");
        }

        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getId,product.getId());
        int res = productInfoMapper.update(product, wrapper);

        if (res < 1){
            log.info("修改失败");
            return new ResponseResult<Product>().setCode(400).setMessage("修改项目经历失败");
        }

        return new ResponseResult<Product>().success();
    }

    @Override
    public ResponseResult<Education> studentEducationUpdate(Education education) {
        if (Objects.isNull(education)){
            return new ResponseResult<Education>().setCode(400).setMessage("参数为空");
        }

        LambdaQueryWrapper<Education> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Education::getId,education.getId());
        int res = educationMapper.update(education, wrapper);
        if (res < 1){
            log.info("修改失败");
            return new ResponseResult<Education>().setCode(400).setMessage("修改失败");
        }

        return new ResponseResult<Education>().success();
    }

    @Override
    public ResponseResult<WorkInfo> studentWorkInfoAdd(WorkInfo workInfo) {
        if (Objects.isNull(workInfo)){
            return new ResponseResult<WorkInfo>().setCode(400).setMessage("参数为空");
        }

        int res = workInfoMapper.insert(workInfo);

        if (res < 1){
            log.info("插入失败");
            return new ResponseResult<WorkInfo>().setCode(400).setMessage("插入失败");
        }

        return new ResponseResult<WorkInfo>().success();
    }

    @Override
    public ResponseResult<Product> studentProductInfoAdd(Product product) {
        if (Objects.isNull(product)){
            return new ResponseResult<Product>().setCode(400).setMessage("参数为空");
        }

        int res = productInfoMapper.insert(product);

        if (res < 1){
            log.info("插入失败");
            return new ResponseResult<Product>().setCode(400).setMessage("插入失败");
        }

        return new ResponseResult<Product>().success();
    }

    @Override
    public ResponseResult<Education> studentEducationAdd(Education education) {
        if (Objects.isNull(education)){
            return new ResponseResult<Education>().setCode(400).setMessage("参数为空");
        }
        int res = educationMapper.insert(education);
        if (res < 1){
            log.info("插入失败");
            return new ResponseResult<Education>().setCode(400).setMessage("插入失败");
        }

        return new ResponseResult<Education>().success();
    }

    @Override
    public ResponseResult<Certificate> studentCertificateAdd(StudentCertificateVO certificateVO) {
        String studentId = certificateVO.getStudentId();
        int sid = Check.checkAndReturnId(studentId);

        if (sid == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<Certificate>().setCode(400).setMessage("id不合法");
        }
        Student student = queryStudentId(studentId);

        if (Objects.isNull(student)){
            log.info("学生用户不存在");
            return new ResponseResult<Certificate>().setCode(400).setMessage("学生用户不存在");
        }

        Own own = new Own();
        own.setCertificateId(certificateVO.getCertificateId());
        own.setStudent_id(sid);
        int res = ownMapper.insert(own);

        if (res < 1){
            log.info("插入失败");
            return new ResponseResult<Certificate>().setCode(400).setMessage("插入失败");
        }
        return new ResponseResult<Certificate>().success();
    }

    @Override
    public ResponseResult<WorkInfo> studentWorkInfoDelete(String id) {
        int workInfoId = Check.checkAndReturnId(id);

        if (workInfoId == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<WorkInfo>().setCode(400).setMessage("id不合法");
        }
        LambdaQueryWrapper<WorkInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkInfo::getId,id);
        int res = workInfoMapper.delete(wrapper);
        if (res < 1){
            log.info("删除失败");
            return new ResponseResult<WorkInfo>().setCode(400).setMessage("删除失败");
        }
        return new ResponseResult<WorkInfo>().success();
    }

    @Override
    public ResponseResult<Product> studentProductInfoDelete(String id) {
        int productId = Check.checkAndReturnId(id);
        if (productId == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<Product>().setCode(400).setMessage("id不合法");
        }

        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getId,productId);
        int res = productInfoMapper.delete(wrapper);
        if (res < 1){
            log.info("删除失败");
            return new ResponseResult<Product>().setCode(400).setMessage("删除失败");
        }

        return new ResponseResult<Product>().success();
    }

    @Override
    public ResponseResult<Education> studentEducationDelete(String id) {
        int educationId = Check.checkAndReturnId(id);
        if (educationId == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<Education>().setCode(400).setMessage("id不合法");
        }

        LambdaQueryWrapper<Education> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Education::getId,id);
        int res = educationMapper.delete(wrapper);
        if (res < 1){
            log.info("删除失败");
            return new ResponseResult<Education>().setCode(400).setMessage("删除失败");
        }

        return new ResponseResult<Education>().success();

    }

    @Override
    public ResponseResult<Certificate> studentCertificateDelete(StudentCertificateVO certificateVO) {
        Integer certificateId = certificateVO.getCertificateId();
        String studentId = certificateVO.getStudentId();
        int sid = Check.checkAndReturnId(studentId);
        if (sid == INVALID_SCAN){
            log.info("id不合法");
            return new ResponseResult<Certificate>().setCode(400).setMessage("id不合法");
        }

        LambdaQueryWrapper<Own> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Own::getStudent_id,sid);
        wrapper.eq(Own::getCertificateId,certificateId);
        int res = ownMapper.delete(wrapper);
        if (res < 1){
            log.info("删除失败");
            return new ResponseResult<Certificate>().setCode(400).setMessage("删除失败");
        }
        return new ResponseResult<Certificate>().success();
    }

    @Override
    @Transactional
    public ResponseResult<ResultCodeEnum> studentUploadFile(Integer studentId, MultipartFile file)
            throws IOException, ParameterIsNullException {
        MyAssert.objectParameterCheck(studentId);
        if (Objects.isNull(file)){
            return new ResponseResult<ResultCodeEnum>().fail(ResultCodeEnum.FILE_IS_NULL);
        }
        Student student = studentMapper.selectById(studentId);
        if (Objects.isNull(student)){
            return new ResponseResult<ResultCodeEnum>().fail(ResultCodeEnum.NOT_FIND_STUDENT);
        }

        COSClient cosClient = OssUtil.getOssClient();
        //获取上传文件输入流
        InputStream inputStream = file.getInputStream();
        //获取文件名称
        String fileName = file.getOriginalFilename();
        fileName = FILE + "/" + fileName;
        com.qcloud.cos.model.ObjectMetadata objectMetadata = new ObjectMetadata();
        PutObjectRequest putObjectRequest =
                new PutObjectRequest(BUCKET_NAME, fileName, inputStream,objectMetadata);
        cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        String  url = "https://"+BUCKET_NAME+"."+"cos"+"."+END_POINT+".myqcloud.com"+"/"+fileName;

        student.setFile(url);
        if (studentMapper.updateById(student) < 1){
            throw new RuntimeException("操作失败");
        }
        return new ResponseResult<ResultCodeEnum>().success();
    }

    @Override
    public ResponseResult editAdvantage(String studentId, String advantage) {
        Student student = studentMapper.selectById(studentId);
        student.setSuperiority(advantage);
        studentMapper.updateById(student);
        return new ResponseResult<ResultCodeEnum>().success();
    }

    @Override
    public ResponseResult<String> queryAdvantage(String studentId) {
        Student student = studentMapper.selectById(studentId);
        return new ResponseResult<String>().success(student.getSuperiority());
    }

    public Student queryStudentId(String id){
        return studentMapper.selectById(id);
    }
}
